import Cookie from 'js-cookie';

const host = "http://api.linwine.space/api/sjk";


/*
    headers: default with Token
*/
function getRequest(url, method, headers, body) {
    if (url === undefined || typeof url !== 'string' || method === undefined || typeof method !== 'string') {
        throw new Error("URL(The first param) and method(The second param) are required and must be string!")
    }
    const cookie = Cookie.get('userData');
    const userData = cookie == undefined ? null : JSON.parse(cookie);
    if (userData == null) {
        throw new Error("Can not get Cookie!");
    }
    if(headers!==undefined && !(headers instanceof Headers) ) {
        throw new Error("The param headers should be class Headers!");
    }
    const h = headers === undefined ? new Headers() : headers;
    h.append("Token", userData['Token']);
    const request = new Request(`${host}${url}`, {
        method: method,
        headers: h,
        body: body
    })
    return fetch(request);
}

export function downloadFiles(file_id, file_name) {
    if(file_id === undefined || file_id === "") {
        console.error("File Id can not be empty!");
        return ;
    }

    getRequest(`/user/download/${file_id}`, "GET")
        .then(res => res.blob())
        .then(blob => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = file_name === undefined ? "" : file_name;
            a.click();
            URL.revokeObjectURL(url);

        })
        .catch((err) => {
            console.error(err);
        })
}


export default getRequest;
